package com.david.func_test.widget

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.view.updateLayoutParams

class BubbleAnimWidget(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
    private var valueAnimator = ValueAnimator.ofInt(0, 30)
    private var items: ArrayList<AnimItemBean> = ArrayList()
    private var itemViews: ArrayList<View> = ArrayList()
    fun setItems(temps: ArrayList<AnimItemBean>?){
        items.clear()
        if (temps != null) {
            items.addAll(temps)
        }
        removeAllViews()
        if (items.size > 0) {
            for ((index, item) in items.withIndex()) {
                val view = ImageView(context)
                val params = LayoutParams(50, 50)
                params.topMargin = 50
                params.leftMargin = (index + 1) * 50
                view.layoutParams = params
                addView(view)
            }
            startAnim()
        }
    }

    private fun startAnim(){
        if (valueAnimator.isRunning) {
            return
        }
        valueAnimator.duration = 1000
        valueAnimator.repeatCount = ValueAnimator.INFINITE
        valueAnimator.repeatMode = ValueAnimator.REVERSE
        valueAnimator.addUpdateListener { animator -> // 获得每次变化后的属性值
            val currentValue = animator.animatedValue as Int

//            view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
//                topMargin = 50 + currentValue
//            }
            for (view in itemViews) {
                (view.layoutParams as FrameLayout.LayoutParams).topMargin = 50 + currentValue
            }
            requestLayout()
        }
        valueAnimator.start()
    }

    fun stopAnim(){
        if (valueAnimator.isRunning) {
            valueAnimator.cancel()
        }
    }

    fun onDestroy(){
        stopAnim()
    }
}

data class AnimItemBean(var text: String, var topMargin:Int = 0)